<template>
  <div class="p-2">
    <transition :enter-active-class="proxy?.animate.searchAnimate.enter" :leave-active-class="proxy?.animate.searchAnimate.leave">
      <div v-show="showSearch" class="mb-[10px]">
        <el-card shadow="hover">
          <el-form ref="queryFormRef" :inline="true" :model="queryParams"  label-width="120px">
            <el-form-item label="描述" prop="description">
              <el-input v-model="queryParams.description" clearable placeholder="请输入描述" @keyup.enter="handleQuery" />
            </el-form-item>
<!--            <el-form-item label="是否删除：0-未删除，1-已删除" prop="isDeleted">-->
<!--              <el-input v-model="queryParams.isDeleted" placeholder="请输入是否删除：0-未删除，1-已删除" clearable @keyup.enter="handleQuery" />-->
<!--            </el-form-item>-->
<!--            <el-form-item label="工单编码" prop="orderCode">-->
<!--              <el-input v-model="queryParams.orderCode" placeholder="请输入工单编码" clearable @keyup.enter="handleQuery" />-->
<!--            </el-form-item>-->
            <el-form-item label="工序编号" prop="processCode">
              <el-input v-model="queryParams.processCode" clearable placeholder="请输入工序编号" @keyup.enter="handleQuery" />
            </el-form-item>
            <el-form-item label="工序名称" prop="processName">
              <el-input v-model="queryParams.processName" clearable placeholder="请输入工序名称" @keyup.enter="handleQuery" />
            </el-form-item>
            <el-form-item label="SAP生产订单号" prop="sapOrderCode">
              <el-input v-model="queryParams.sapOrderCode" clearable placeholder="请输入SAP生产订单号" @keyup.enter="handleQuery" />
            </el-form-item>
            <el-form-item label="节拍时间" prop="beatTime">
              <el-input v-model="queryParams.beatTime" clearable placeholder="请输入节拍时间" @keyup.enter="handleQuery" />
            </el-form-item>
            <el-form-item label="车厢编码" prop="carriageCode">
              <el-input v-model="queryParams.carriageCode" clearable placeholder="请输入车厢编码" @keyup.enter="handleQuery" />
            </el-form-item>
            <el-form-item label="工位" prop="workstationId">
              <el-select
                v-model="queryParams.workstationId"
                :loading="workstationLoading"
                :remote-method="handleWorkstationSearch"
                clearable
                filterable
                placeholder="请选择工位"
                remote
              >
                <el-option
                  v-for="item in workstationOptions"
                  :key="item.id"
                  :label="item.workstationName"
                  :value="item.id"
                >
                  <span>{{ item.workstationName }}</span>
                  <span class="text-gray-500 ml-2">({{ item.workstationCode }})</span>
                </el-option>
              </el-select>
            </el-form-item>
            <el-form-item label="工序顺序" prop="sequence">
              <el-input v-model="queryParams.sequence" clearable placeholder="请输入工序顺序" @keyup.enter="handleQuery" />
            </el-form-item>
            <el-form-item label="计划开始时间" prop="planStartTime">
              <el-date-picker v-model="queryParams.planStartTime"
                clearable
                placeholder="请选择计划开始时间"
                type="datetime"
                value-format="YYYY-MM-DD HH:mm:ss"
              />
            </el-form-item>
            <el-form-item label="计划结束时间" prop="planEndTime">
              <el-date-picker v-model="queryParams.planEndTime"
                clearable
                placeholder="请选择计划结束时间"
                type="datetime"
                value-format="YYYY-MM-DD HH:mm:ss"
              />
            </el-form-item>
            <el-form-item label="实际开始时间" prop="actualStartTime">
              <el-date-picker v-model="queryParams.actualStartTime"
                clearable
                placeholder="请选择实际开始时间"
                type="datetime"
                value-format="YYYY-MM-DD HH:mm:ss"
              />
            </el-form-item>
            <el-form-item label="实际结束时间" prop="actualEndTime">
              <el-date-picker v-model="queryParams.actualEndTime"
                clearable
                placeholder="请选择实际结束时间"
                type="datetime"
                value-format="YYYY-MM-DD HH:mm:ss"
              />
            </el-form-item>
           <el-form-item label="当前操作人" prop="operatorId">
             <!-- <el-input v-model="queryParams.operatorId" placeholder="请输入当前操作人ID" clearable @keyup.enter="handleQuery" /> -->

             <el-select
                v-model="queryParams.operatorId"
                :loading="operatorIdLoading"
                :remote-method="handleOperatorIdSearch"
                clearable
                filterable
                placeholder="请选择"
                remote
              >
                <el-option
                  v-for="item in operatorOptions"
                  :key="item.userId"
                  :label="item.nickName"
                  :value="item.userId"
                >
                  <span>{{ item.nickName }}</span>
                  <!-- <span class="text-gray-500 ml-2">({{ item.workstationCode }})</span> -->
                </el-option>
              </el-select>
            </el-form-item>
            <el-form-item>
              <el-button icon="Search" type="primary" @click="handleQuery">搜索</el-button>
              <el-button icon="Refresh" @click="resetQuery">重置</el-button>
            </el-form-item>
          </el-form>
        </el-card>
      </div>
    </transition>

    <el-card shadow="never">
      <!-- <template #header>
        <el-row :gutter="10" class="mb8">
          <el-col :span="1.5">
            <el-button v-hasPermi="['painting:workOrder:add']" icon="Plus" plain type="primary" @click="handleAdd">新增</el-button>
          </el-col>
          <el-col :span="1.5">
            <el-button v-hasPermi="['painting:workOrder:edit']" :disabled="single" icon="Edit" plain type="success" @click="handleUpdate()">修改</el-button>
          </el-col>
          <el-col :span="1.5">
            <el-button v-hasPermi="['painting:workOrder:remove']" :disabled="multiple" icon="Delete" plain type="danger" @click="handleDelete()">删除</el-button>
          </el-col>
          <el-col :span="1.5">
            <el-button v-hasPermi="['painting:workOrder:export']" icon="Download" plain type="warning" @click="handleExport">导出</el-button>
          </el-col>
          <el-col :span="1.5">
            <el-button v-hasPermi="['painting:workOrder:start']" :disabled="single" icon="VideoPlay" plain type="success" @click="handleStart">开工</el-button>
          </el-col>
          <el-col :span="1.5">
            <el-button v-hasPermi="['painting:workOrder:finish']" :disabled="single" icon="CircleCheck" plain type="primary" @click="handleFinish">完工</el-button>
          </el-col>
          <right-toolbar v-model:showSearch="showSearch" @queryTable="getList"></right-toolbar>
        </el-row>
      </template> -->

      <el-table v-loading="loading" :data="workOrderList" style="width: 100%"  @selection-change="handleSelectionChange">
        <el-table-column align="center" type="selection" width="55" />
        <!-- <el-table-column v-if="true" align="center" label="主键ID" prop="id" /> -->
        <el-table-column align="center" label="状态" prop="status" width="150">
          <template #default="scope">
            <el-tag :type="statusMap[scope.row.status]?.type">
              {{ statusMap[scope.row.status]?.text }}
            </el-tag>
          </template>
        </el-table-column>
        <el-table-column align="center" label="描述" prop="description"  width="150"/>
<!--        <el-table-column label="是否删除：0-未删除，1-已删除" align="center" prop="isDeleted" />-->
<!--        <el-table-column label="工单编码" align="center" prop="orderCode" />-->
        <el-table-column align="center" label="工序编号" prop="processCode"  width="150"/>
        <el-table-column align="center" label="工序名称" prop="processName"  width="150"/>
        <el-table-column align="center" label="SAP生产订单号" prop="sapOrderCode"  width="150"/>
        <el-table-column align="center" label="节拍时间" prop="beatTime"  width="150"/>
        <el-table-column align="center" label="车厢编码" prop="carriageCode"  width="150"/>
        <el-table-column align="center" label="工位" prop="workstationId" width="150">
          <template #default="scope">
            <span>{{ getWorkstationName(scope.row.workstationId) }}</span>
          </template>
        </el-table-column>
        <el-table-column align="center" label="工序顺序" prop="sequence"  width="150"/>
        <el-table-column align="center" label="计划开始时间" prop="planStartTime" width="150">
          <template #default="scope">
            <span>{{ parseTime(scope.row.planStartTime, '{y}-{m}-{d} {h}:{i}:{s}') }}</span>
          </template>
        </el-table-column>
        <el-table-column align="center" label="计划结束时间" prop="planEndTime" width="150">
          <template #default="scope">
            <span>{{ parseTime(scope.row.planEndTime, '{y}-{m}-{d} {h}:{i}:{s}') }}</span>
          </template>
        </el-table-column>
        <el-table-column align="center" label="实际开始时间" prop="actualStartTime" width="150">
          <template #default="scope">
            <span>{{ parseTime(scope.row.actualStartTime, '{y}-{m}-{d} {h}:{i}:{s}') }}</span>
          </template>
        </el-table-column>
        <el-table-column align="center" label="实际结束时间" prop="actualEndTime"  width="150">
          <template #default="scope">
            <span>{{ parseTime(scope.row.actualEndTime, '{y}-{m}-{d} {h}:{i}:{s}') }}</span>
          </template>
        </el-table-column>
        <el-table-column align="center" label="当前操作人" prop="operatorName"  width="150"/>
        <el-table-column align="center" class-name="small-padding fixed-width" fixed="right" label="操作" width="150">
          <template #default="scope">
            <!-- <el-tooltip content="修改" placement="top">
              <el-button v-hasPermi="['painting:workOrder:edit']" icon="Edit" link type="primary" @click="handleUpdate(scope.row)"></el-button>
            </el-tooltip>
            <el-tooltip content="删除" placement="top">
              <el-button v-hasPermi="['painting:workOrder:remove']" icon="Delete" link type="primary" @click="handleDelete(scope.row)"></el-button>
            </el-tooltip> -->
            <el-button link type="primary" @click="handleUpdate(scope.row)">编辑</el-button>
            <el-button link type="primary" @click="handleIssued(scope.row)">下发</el-button>
            <el-button link type="primary" @click="">开工</el-button>
            <el-button link type="primary" @click="">完工</el-button>
            <el-button link type="primary" @click="handleAbnormal(scope.row)">异常上报</el-button>
            <el-button link type="primary" @click="">自检</el-button>
            <el-button link type="primary" @click="handleInspection(scope.row)">互检</el-button>
          </template>
        </el-table-column>
      </el-table>

      <pagination v-show="total > 0" v-model:limit="queryParams.pageSize" v-model:page="queryParams.pageNum" :total="total" @pagination="getList" />
    </el-card>
    <!-- 添加或修改工单对话框 -->
    <el-dialog v-model="dialog.visible" :title="dialog.title" append-to-body width="1000px">
      <el-form ref="workOrderFormRef" :model="form" :rules="rules" label-width="150px">
        <el-form-item label="描述" prop="description">
            <el-input v-model="form.description" placeholder="请输入内容" type="textarea" />
        </el-form-item>
<!--        <el-form-item label="是否删除：0-未删除，1-已删除" prop="isDeleted">-->
<!--          <el-input v-model="form.isDeleted" placeholder="请输入是否删除：0-未删除，1-已删除" />-->
<!--        </el-form-item>-->
<!--        <el-form-item label="工单编码" prop="orderCode">-->
<!--          <el-input v-model="form.orderCode" placeholder="请输入工单编码" />-->
<!--        </el-form-item>-->
        <el-form-item label="工序编号" prop="processCode">
          <el-input v-model="form.processCode" placeholder="请输入工序编号" />
        </el-form-item>
        <el-form-item label="工序名称" prop="processName">
          <el-input v-model="form.processName" placeholder="请输入工序名称" />
        </el-form-item>
        <el-form-item label="SAP生产订单号" prop="sapOrderCode">
          <el-input v-model="form.sapOrderCode" placeholder="请输入SAP生产订单号" />
        </el-form-item>
        <el-form-item label="节拍时间" prop="beatTime">
          <el-input v-model="form.beatTime" placeholder="请输入节拍时间" />
        </el-form-item>
        <el-form-item label="车厢编码" prop="carriageCode">
          <el-input v-model="form.carriageCode" placeholder="请输入车厢编码" />
        </el-form-item>
        <el-form-item label="工位" prop="workstationId">
          <el-select
            v-model="form.workstationId"
            :loading="workstationLoading"
            :remote-method="handleWorkstationSearch"
            clearable
            filterable
            placeholder="请选择工位"
            remote
          >
            <el-option
              v-for="item in workstationOptions"
              :key="item.id"
              :label="item.workstationName"
              :value="item.id"
            >
              <span>{{ item.workstationName }}</span>
              <span class="text-gray-500 ml-2">({{ item.workstationCode }})</span>
            </el-option>
          </el-select>
        </el-form-item>
<!--        <el-form-item label="工序顺序" prop="sequence">-->
<!--          <el-input v-model="form.sequence" placeholder="请输入工序顺序" />-->
<!--        </el-form-item>-->
        <el-form-item label="计划开始时间" prop="planStartTime">
          <el-date-picker v-model="form.planStartTime"
            clearable
            placeholder="请选择计划开始时间"
            type="datetime"
            value-format="YYYY-MM-DD HH:mm:ss">
          </el-date-picker>
        </el-form-item>
        <el-form-item label="计划结束时间" prop="planEndTime">
          <el-date-picker v-model="form.planEndTime"
            clearable
            placeholder="请选择计划结束时间"
            type="datetime"
            value-format="YYYY-MM-DD HH:mm:ss">
          </el-date-picker>
        </el-form-item>
        <el-form-item label="实际开始时间" prop="actualStartTime">
          <el-date-picker v-model="form.actualStartTime"
            clearable
            placeholder="请选择实际开始时间"
            type="datetime"
            value-format="YYYY-MM-DD HH:mm:ss">
          </el-date-picker>
        </el-form-item>
        <el-form-item label="实际结束时间" prop="actualEndTime">
          <el-date-picker v-model="form.actualEndTime"
            clearable
            placeholder="请选择实际结束时间"
            type="datetime"
            value-format="YYYY-MM-DD HH:mm:ss">
          </el-date-picker>
        </el-form-item>
        <el-form-item label="状态" prop="status">
          <el-select v-model="form.status" placeholder="请选择状态">
            <el-option
              v-for="(item, key) in statusMap"
              :key="key"
              :label="item.text"
              :value="Number(key)"
            />
          </el-select>
        </el-form-item>
       <el-form-item label="当前操作人" prop="operatorId">
         <!-- <el-input v-model="form.operatorId" placeholder="请输入当前操作人ID" /> -->
         <el-select
                v-model="form.operatorId"
                :loading="operatorIdLoading"
                :remote-method="handleOperatorIdSearch"
                clearable
                filterable
                placeholder="请选择"
                remote
              >
                <el-option
                  v-for="item in operatorOptions"
                  :key="item.userId"
                  :label="item.nickName"
                  :value="item.userId"
                >
                  <span>{{ item.nickName }}</span>
                  <!-- <span class="text-gray-500 ml-2">({{ item.workstationCode }})</span> -->
                </el-option>
              </el-select>
      </el-form-item>
      </el-form>
      <template #footer>
        <div class="dialog-footer">
          <el-button :loading="buttonLoading" type="primary" @click="submitForm">确 定</el-button>
          <el-button @click="cancel">取 消</el-button>
        </div>
      </template>
    </el-dialog>

     <!-- 下发 -->
     <el-dialog v-model="dialogIssued.visible" :title="dialogIssued.title" append-to-body width="800px">
      <el-form ref="workOrderFormRef" :model="formAbnormal" :rules="rules" label-width="120px">
        <el-form-item label="工位" prop="isDeleted">

          <el-select v-model="form.operatorId" :loading="workstationLoading" :remote-method="handleIssuedList" clearable
            filterable placeholder="请选择" remote>
            <el-option v-for="item in issuedList" :key="item.id" :label="item.workstationName"
              :value="item.id">
              <span>{{ item.workstationName }}</span>
              <!-- <span class="text-gray-500 ml-2">({{ item.workstationCode }})</span> -->
            </el-option>
          </el-select>
        </el-form-item>
      </el-form>
      <template #footer>
        <div class="dialog-footer">
          <el-button :loading="buttonLoading" type="primary" @click="submitForm">确 定</el-button>
          <el-button @click="cancelAbnormal">取 消</el-button>
        </div>
      </template>
    </el-dialog>
    <!-- 异常上报 -->
    <el-dialog v-model="dialogAbnormal.visible" :title="dialogAbnormal.title" append-to-body width="800px">
      <el-form ref="workOrderFormRef" :model="formAbnormal" :rules="rules" label-width="120px">
        <el-form-item label="异常类别" prop="status">
          <el-select v-model="formAbnormal.status" class="m-2" placeholder="请选择" size="large">
            <el-option v-for="item in optionsStatus" :key="item.value" :label="item.label" :value="item.value" />
          </el-select>
        </el-form-item>
        <el-form-item label="异常描述" prop="description">
          <el-input v-model="formAbnormal.description" placeholder="请输入" type="textarea" />
        </el-form-item>
        <el-form-item label="异常处理人" prop="isDeleted">
          <!-- <el-input v-model="form.isDeleted" placeholder="请输入是否删除：0-未删除，1-已删除" /> -->
          <!-- <el-select v-model="formAbnormal.isDeleted" class="m-2" placeholder="请选择">
            <el-option v-for="item in isDeletedOptions" :key="item.value" :label="item.label" :value="item.value" />
          </el-select> -->
          <el-select v-model="form.operatorId" :loading="operatorIdLoading" :remote-method="handleOperatorIdSearch"
            clearable filterable placeholder="请选择" remote>
            <el-option v-for="item in operatorOptions" :key="item.userId" :label="item.nickName" :value="item.userId">
              <span>{{ item.nickName }}</span>
              <!-- <span class="text-gray-500 ml-2">({{ item.workstationCode }})</span> -->
            </el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="异常上报人" prop="operator">
          <el-input v-model="formAbnormal.operator" placeholder="请输入作业人ID" />
        </el-form-item>
      </el-form>
      <template #footer>
        <div class="dialog-footer">
          <el-button :loading="buttonLoading" type="primary" @click="submitForm">确 定</el-button>
          <el-button @click="cancelAbnormal">取 消</el-button>
        </div>
      </template>
    </el-dialog>
    <!-- 互检 -->
    <el-dialog v-model="dialogInspection.visible" :title="dialogInspection.title" append-to-body width="500px">
      <el-form ref="workOrderFormRef" :model="formInspection" :rules="rules" label-width="120px">

        <el-form-item label="账号" prop="user">
          <el-input v-model="formInspection.user" placeholder="请输入账号" />
        </el-form-item>
        <el-form-item label="密码" prop="pwd">
          <el-input v-model="formInspection.pwd" placeholder="请输入密码" type="password" />
        </el-form-item>
      </el-form>
      <template #footer>
        <div class="dialog-footer">
          <el-button :loading="buttonLoading" type="primary" @click="submitFormInspection">确 定</el-button>
          <el-button @click="cancelInspection">取 消</el-button>
        </div>
      </template>
    </el-dialog>
  </div>
</template>

<script lang="ts" name="WorkOrder" setup>
import {addWorkOrder, delWorkOrder, getWorkOrder, listWorkOrder, updateWorkOrder} from '@/api/painting/workOrder';
import {WorkOrderForm, WorkOrderQuery, WorkOrderVO} from '@/api/painting/workOrder/types';
import {listWorkstation} from '@/api/painting/workstation';
import {WorkstationVO} from '@/api/painting/workstation/types';
import { useUserStore } from '@/store/modules/user';
import api from '@/api/system/user';
// import {OperatorVO} from '@/api/painting/workstation/types'
import request from '@/utils/request';
const { proxy } = getCurrentInstance() as ComponentInternalInstance;

// 状态映射
const statusMap = {
  0: { text: '待执行', type: 'info' },
  1: { text: '执行中', type: 'primary' },
  2: { text: '已完成', type: 'success' },
  3: { text: '已取消', type: 'danger' }
};

const workOrderList = ref<WorkOrderVO[]>([]);
const workstationOptions = ref<WorkstationVO[]>([]);
const workstationLoading = ref(false);
const buttonLoading = ref(false);
const loading = ref(true);
const showSearch = ref(true);
const ids = ref<Array<string | number>>([]);
const single = ref(true);
const multiple = ref(true);
const total = ref(0);

const queryFormRef = ref<ElFormInstance>();
const workOrderFormRef = ref<ElFormInstance>();

// 当前操作人ID
const operatorIdLoading = ref(false);
const operatorOptions = ref<UserVO[]>([]);

const dateRange = ref<[DateModelType, DateModelType]>(['', '']);

const userStore = useUserStore();
// 可以获取以下用户信息
const userId = userStore.userId;
const tenantId = userStore.tenantId;
const nickname = userStore.nickname;
const avatar = userStore.avatar;
const roles = userStore.roles;
const permissions = userStore.permissions;
// 选择工位
const issuedList = ref([]);
const optionsStatus = ref([
  {
    value: 0,
    label: '禁用',
  },
  {
    value: 1,
    label: '启用',
  },
])

const dialog = reactive<DialogOption>({
  visible: false,
  title: ''
});

const initFormData: WorkOrderForm = {
  id: undefined,
  status: undefined,
  description: undefined,
  isDeleted: undefined,
  orderCode: undefined,
  processCode: undefined,
  processName: undefined,
  sapOrderCode: undefined,
  beatTime: undefined,
  carriageCode: undefined,
  workstationId: undefined,
  sequence: undefined,
  planStartTime: undefined,
  planEndTime: undefined,
  actualStartTime: undefined,
  actualEndTime: undefined,
  operatorId: undefined
}
const formAbnormal = ref({
  status: null,
  description: null,
  isDeleted: null,
  operator: null
})
const formInspection = ref({
  user: null,
  pwd: null,
})
const data = reactive<PageData<WorkOrderForm, WorkOrderQuery>>({
  form: {...initFormData},
  queryParams: {
    pageNum: 1,
    pageSize: 10,
    status: undefined,
    description: undefined,
    isDeleted: undefined,
    orderCode: undefined,
    processCode: undefined,
    processName: undefined,
    sapOrderCode: undefined,
    beatTime: undefined,
    carriageCode: undefined,
    workstationId: undefined,
    sequence: undefined,
    planStartTime: undefined,
    planEndTime: undefined,
    actualStartTime: undefined,
    actualEndTime: undefined,
    operatorId: undefined,
    params: {
    }
  },
  rules: {
    id: [
      { required: true, message: "主键ID不能为空", trigger: "blur" }
    ],
    status: [
      { required: true, message: "状态：0-待执行，1-执行中，2-已完成，3-已取消不能为空", trigger: "change" }
    ],
    isDeleted: [
      { required: true, message: "是否删除：0-未删除，1-已删除不能为空", trigger: "blur" }
    ],
    orderCode: [
      { required: true, message: "工单编码不能为空", trigger: "blur" }
    ],
    processCode: [
      { required: true, message: "工序编号不能为空", trigger: "blur" }
    ],
    processName: [
      { required: true, message: "工序名称不能为空", trigger: "blur" }
    ],
    sapOrderCode: [
      { required: true, message: "SAP生产订单号不能为空", trigger: "blur" }
    ],
    beatTime: [
      { required: true, message: "节拍时间不能为空", trigger: "blur" }
    ],
    carriageCode: [
      { required: true, message: "车厢编码不能为空", trigger: "blur" }
    ],
    workstationId: [
      { required: true, message: "工位ID不能为空", trigger: "blur" }
    ],
    sequence: [
      { required: true, message: "工序顺序不能为空", trigger: "blur" }
    ],
    user: [
      { required: true, message: "账号不能为空", trigger: "blur" }
    ],
    pwd: [
      { required: true, message: "密码不能为空", trigger: "blur" }
    ],
  }
});

const { queryParams, form, rules } = toRefs(data);
// 工位列表数据

const handleIssuedList = async (query: string) => {
  workstationLoading.value = true;
  try {
    const res = await listWorkstation({
      pageSize: 10,
      pageNum: 1
    });
    issuedList.value = res.rows;
  } finally {
    workstationLoading.value = false;
  }
}
// // 异常处理人
// const handleOperatorIdSearch = async (query: string) => {
//   operatorIdLoading.value = true;
//   try {
//     // const res = await listUser({
//     //   workstationName: query,
//     //   pageSize: 10,
//     //   pageNum: 1
//     // });
//     const res = await api.listUser(proxy?.addDateRange(queryParams.value, ''));

//     operatorOptions.value = res.rows;
//   } finally {
//     operatorIdLoading.value = false;
//   }
// }
// 异常上报
const dialogAbnormal = reactive<DialogOption>({
  visible: false,
  title: ''
});
// 互检人弹窗
const dialogInspection = reactive<DialogOption>({
  visible: false,
  title: ''
});
// 下发
const dialogIssued= reactive<DialogOption>({
  visible: false,
  title: ''
});
/** 查询工单列表 */
const getList = async () => {
  loading.value = true;
  const res = await listWorkOrder(queryParams.value);
  workOrderList.value = res.rows;
  total.value = res.total;
  loading.value = false;
}

/** 取消按钮 */
const cancel = () => {
  reset();
  dialog.visible = false;
}


// 下发
const handleIssued = (row) => {
  console.log(row)
  dialogIssued.visible = true;
  dialogIssued.title = "下发";
}
// 异常上报
const handleAbnormal = (row) => {
  console.log(row)
  dialogAbnormal.visible = true;
  dialogAbnormal.title = "异常上报";
}
const cancelAbnormal = () => {
  reset();
  dialogAbnormal.visible = false;
}
// 互检人
const handleInspection = (row) => {
  console.log(row)
  dialogInspection.visible = true;
  dialogInspection.title = "互检人信息";
}
const cancelInspection = () => {
  reset();
  dialogInspection.visible = false;
}
// 互检信息
const submitFormInspection = () => {
  workOrderFormRef.value?.validate(async (valid: boolean) => {
    if (valid) {
      buttonLoading.value = true;
      // if (form.value.id) {
      //   await updateWorkPlan(form.value).finally(() => buttonLoading.value = false);
      // } else {
      //   await addWorkPlan(form.value).finally(() => buttonLoading.value = false);
      // }
      proxy?.$modal.msgSuccess("操作成功");
      dialog.visible = false;
      await getList();
    }
  });
}
/** 表单重置 */
const reset = () => {
  form.value = {...initFormData};
  workOrderFormRef.value?.resetFields();
}

/** 搜索按钮操作 */
const handleQuery = () => {
  queryParams.value.pageNum = 1;
  getList();
}

/** 重置按钮操作 */
const resetQuery = () => {
  queryFormRef.value?.resetFields();
  handleQuery();
}

/** 多选框选中数据 */
const handleSelectionChange = (selection: WorkOrderVO[]) => {
  ids.value = selection.map(item => item.id);
  single.value = selection.length != 1;
  multiple.value = !selection.length;
}

/** 新增按钮操作 */
const handleAdd = () => {
  reset();
  dialog.visible = true;
  dialog.title = "添加工单";
}

/** 处理工位搜索 */
const handleWorkstationSearch = async (query: string) => {
  workstationLoading.value = true;
  try {
    const res = await listWorkstation({
      workstationName: query,
      pageSize: 10,
      pageNum: 1
    });
    workstationOptions.value = res.rows;
  } finally {
    workstationLoading.value = false;
  }
}
const handleOperatorIdSearch = async (query: string) => {
  operatorIdLoading.value = true;
  try {
    // const res = await listUser({
    //   workstationName: query,
    //   pageSize: 10,
    //   pageNum: 1
    // });
  const res = await api.listUser(proxy?.addDateRange(queryParams.value,''));

  operatorOptions.value = res.rows;
  } finally {
    operatorIdLoading.value = false;
  }
}

/** 获取工位名称 */
const getWorkstationName = (id: string | number) => {
  const workstation = workstationOptions.value.find(item => item.id === id);
  return workstation ? `${workstation.workstationName} (${workstation.workstationCode})` : id;
}

/** 获取工位详情 */
const getWorkstationDetail = async (id: string | number) => {
  if (!id) return;
  workstationLoading.value = true;
  try {
    const res = await listWorkstation({
      id: id,
      pageSize: 1,
      pageNum: 1
    });
    if (res.rows.length > 0) {
      workstationOptions.value = res.rows;
    }
  } finally {
    workstationLoading.value = false;
  }
}

/** 修改按钮操作 */
const handleUpdate = async (row?: WorkOrderVO) => {
  reset();
  const _id = row?.id || ids.value[0]
  const res = await getWorkOrder(_id);
  Object.assign(form.value, res.data);
  // 获取工位详情用于回显
  if (form.value.workstationId) {
    await getWorkstationDetail(form.value.workstationId);
  }
  dialog.visible = true;
  dialog.title = "修改工单";
}

/** 提交按钮 */
const submitForm = () => {
  workOrderFormRef.value?.validate(async (valid: boolean) => {
    if (valid) {
      buttonLoading.value = true;
      if (form.value.id) {
        await updateWorkOrder(form.value).finally(() =>  buttonLoading.value = false);
      } else {
        await addWorkOrder(form.value).finally(() =>  buttonLoading.value = false);
      }
      proxy?.$modal.msgSuccess("操作成功");
      dialog.visible = false;
      await getList();
    }
  });
}

/** 删除按钮操作 */
const handleDelete = async (row?: WorkOrderVO) => {
  const _ids = row?.id || ids.value;
  await proxy?.$modal.confirm('是否确认删除工单编号为"' + _ids + '"的数据项？').finally(() => loading.value = false);
  await delWorkOrder(_ids);
  proxy?.$modal.msgSuccess("删除成功");
  await getList();
}

/** 导出按钮操作 */
const handleExport = () => {
  proxy?.download('painting/workOrder/export', {
    ...queryParams.value
  }, `workOrder_${new Date().getTime()}.xlsx`)
}

/** 开工按钮操作 */
const handleStart = async () => {
  const id = ids.value[0];
  await proxy?.$modal.confirm('是否确认开工工单编号为"' + id + '"的数据项？');
  await request.post(`/painting/workOrder/start/${id}`);
  proxy?.$modal.msgSuccess("开工成功");
  await getList();
}

/** 完工按钮操作 */
const handleFinish = async () => {
  const id = ids.value[0];
  await proxy?.$modal.confirm('是否确认完工工单编号为"' + id + '"的数据项？');
  await request.post(`/painting/workOrder/finish/${id}`);
  proxy?.$modal.msgSuccess("完工成功");
  await getList();
}

onMounted(() => {
  getList();
});
</script>
